import { useEffect, useRef } from 'react';
import { WS } from './WebSocket';

interface WebSocketService {
  send: (message: string) => void;
  addMessageListener: (listener: (message: string) => void) => void;
}

const useWebSocket = (url: string): WebSocketService => {
  const socketRef = useRef<WS | null>(null);
  const messageListeners = useRef<((message: string) => void)[]>([]);

  useEffect(() => {
    const ws = new WS({
      wsUrl: url,

      onConnect: () => {
        // websocket的连接成功业务逻辑
      },
      onMessage: (event) => {
        // 接收到客户端数据逻辑
        messageListeners.current.forEach((listener) => {
          console.log('接收到客户消息:{}', event);
          listener(JSON.stringify(event.data));
        });
      },
      onClose: (err) => {
        // 通信连接关闭逻辑
        console.log('ws通信关闭:{}', err);
      },
      onError: (err) => {
        // 通信发送错误逻辑
        console.log('ws通信发送错误:{}', err);
        socketRef.current?.reconnect();
      },
    });
    socketRef.current = ws;

    // 建立连接
    ws.connect();

    return () => {
      ws.close();
    };
  }, [url]);

  const send = (message: string) => {
    if (socketRef.current && socketRef.current.state === WebSocket.OPEN) {
      socketRef.current.sendMessage(
        { message },
        (data) => {
          console.log('成功回调:{}', data);
        },
        (error) => {
          console.log('失败回调:{}', error);
        },
      );
    }
  };
  const addMessageListener = (listener: (message: string) => void) => {
    messageListeners.current.push(listener);
  };

  return { send, addMessageListener };
};

export default useWebSocket;
